package cn.fenqing.demo.demo.exception;

import cn.fenqing.validation.bean.ValidationErrorInfo;
import cn.fenqing.validation.exception.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 12869
 */
@RestControllerAdvice
@Slf4j
public class MyExceptionHandler {

    @ExceptionHandler(value = ValidationException.class)
	public Map<String, Object> exceptionHandler(ValidationException e){
		Method method = e.getMethod();
		log.info("方法：{}", method);
		List<ValidationErrorInfo> validationErrorInfos =
				e.getValidationErrorInfos();
		StringBuilder sb = new StringBuilder();
		validationErrorInfos.forEach(validationErrorInfo -> {
			List<String> message = validationErrorInfo.getMessage();
			String parameterName = validationErrorInfo.getParameterName();
			int index = validationErrorInfo.getIndex();
			log.info("{}:{},{}", index, parameterName, String.join(",\n", message));
			sb.append(String.join(",\n", message)).append("/");
		});
		System.out.println("未知异常！原因是:"+e);
		Map<String, Object> res = new HashMap<>(4);
		res.put("code", 500);
		res.put("message", sb.toString());
		res.put("data", validationErrorInfos);
       	return res;
    }
}